<?php

declare(strict_types=1);

namespace JfbQueue\Process;

use Hyperf\Process\ProcessManager;
use JfbQueue\Driver\DriverInterface;
use Hyperf\Context\ApplicationContext;
use Hyperf\Contract\ConfigInterface;
use Hyperfx\Framework\Logger\Logx;
use JfbQueue\DriverFactory;
use Psr\Container\ContainerInterface;
use Hyperf\Process\AbstractProcess;

class ReloadMessageProcess extends AbstractProcess {
    
    protected int $restartInterval = 10;
    
    private int $maxSize = 2000;
    
    protected DriverFactory $drvier;
    public function __construct(ContainerInterface $container)
    {
        parent::__construct($container);
        $this->drvier = ApplicationContext::getContainer()->get(DriverFactory::class);
    }

    public function handle(): void
    {
        $arrQueueNames = $this->drvier->getCanReloadQueues();
        if (empty($arrQueueNames)) {
            return;
        }
        $intReloadTime = $this->drvier->getReloadTime();

        while (ProcessManager::isRunning()) {
            $this->maxSize--;
            foreach ($arrQueueNames as $queueName) {
                if ($this->drvier->get($queueName)->reload()) {
                    Logx::get()->debug('Reload message success', [
                        'queue' => $queueName,
                    ]);
                }
            }
            if ($this->maxSize < 1) {
                break;
            }
            sleep($intReloadTime);
        }
    }
    
    public function isEnable($server): bool
    {
        return $this->drvier->isEnabledReload();
    }
}